package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.common.utils.DateUtil;
import com.common.utils.DateUtil2;
import com.common.utils.Result;
import com.common.utils.StringUtil;
import com.entity.Node;
import com.entity.TaskRecord;
import com.mapper.TaskRecordMapper;
import com.service.NodeService;
import com.service.TaskRecordService;
import com.vo.FlowVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wty
 * @since 2022-01-06
 */
@Service
public class TaskRecordServiceImpl extends ServiceImpl<TaskRecordMapper, TaskRecord> implements TaskRecordService {

    @Autowired
    private NodeService nodeService;
    /**
     * 添加，修改记录
     * @param taskRecord
     * @return
     */
    @Override
    public Result updateTaskRecord(TaskRecord taskRecord) {
        String addTime = taskRecord.getAddTime();
        if(StringUtil.isEmpty(addTime)){
            taskRecord.setAddTime(DateUtil.getDate_yyyyMMdd());
        }

        Wrapper<TaskRecord> wr=new EntityWrapper<>();
        wr.eq("add_time", taskRecord.getAddTime());
        wr.eq("task_id",taskRecord.getTaskId());
        TaskRecord vo = this.selectOne(wr);
        if(null==vo){//添加操作
            this.insert(taskRecord);
        }else{
            taskRecord.setId(vo.getId());
            this.updateById(taskRecord);
        }
        return Result.success("修改成功");
    }

    /**
     *
     * @return
     */
    @Override
    public Result getTaskList() {

        Wrapper<TaskRecord> twr=new EntityWrapper<>();
        twr.eq("add_time",DateUtil.getDate_yyyyMMdd());
        List<TaskRecord> taskRecords = this.selectList(twr);
        if(!CollectionUtils.isEmpty(taskRecords)){
            this.process(taskRecords);
            return Result.success(taskRecords);
        }

        Wrapper<Node> wr=new EntityWrapper<>();
        List<Node> nodes = nodeService.selectList(wr);

        List<TaskRecord> records=new ArrayList<>();
        if(!CollectionUtils.isEmpty(nodes)){
            for (Node node : nodes) {
                TaskRecord record=new TaskRecord()  ;
                record.setAddTime(DateUtil.getDate_yyyyMMdd());
                record.setTaskId(node.getId());
                record.setName(node.getName());
                records.add(record);
            }
        }

        if(!CollectionUtils.isEmpty(records)){
            this.insertBatch(records);
        }

        this.process(records);
        return  Result.success(records);
    }



    /**
     *
     * @param flowVo
     * @return
     */
    @Override
    public String flow(FlowVo flowVo) {

        String method = flowVo.getMethod();
        String input_type = flowVo.getInput_type();
        String appid = flowVo.getAppid();
        if("create".equals(method)){
            String call_source = flowVo.getCall_source();///呼叫来源 ，比如队列外呼就是 queuedialer
            String source_name = flowVo.getSource_name();//任务名称--对应流程名字
            System.out.println("call_source = " + call_source);
            System.out.println("source_name = " + source_name);

            Map<String,Object>  flowMap=new TreeMap<>();
            flowMap.put("action","cti_play_and_detect_speech");
            flowMap.put("argument","'1' '32' '0' '0.3' '127.0.0.1:9988' '120' '800' '5000' '20000' '' '' '"+appid+"' '1' '\\${strftime(%Y-%m-%d)}' 'wav'");
            //tts设置
            Map<String,String> ttsMap=new TreeMap<>();
            ttsMap.put("ttsurl","http://127.0.0.1:9989/tts");
            ttsMap.put("ttsvoicename","");
            ttsMap.put("ttsconfig","");
            ttsMap.put("ttsengine","");
            ttsMap.put("ttsvolume","0");
            ttsMap.put("ttsspeechrate","0");
            ttsMap.put("ttspitchrate","0");
            flowMap.put("tts",ttsMap);
//"tts"=>array("ttsurl"=>"http://down.ddrj.com:9989/tts","ttsvoicename"=>"","ttsconfig"=>"","ttsengine"=>"","ttsvolume"=>0,"ttsspeechrate"=>0,"ttspitchrate"=>0),
            List<String>  playbacksList=new ArrayList<>();
            playbacksList.add("欢迎你，请说话");
            flowMap.put("playbacks",playbacksList);

            flowMap.put("sound_file_dir","");//声音文件路径
            //回调参数
            flowMap.put("privatedata","start");
            flowMap.put("quickresponse","true");

            List<String> pre_tts_text_list=new ArrayList<>();
            pre_tts_text_list.add("徐先生");
            flowMap.put("pre_tts_text",pre_tts_text_list);
            flowMap.put("log","create succeed");

            return JSONObject.toJSONString(flowMap);

        }else if("input".equals(method)){

            if("text".equals(input_type)){//asr
                String input_args = flowVo.getInput_args();
                String startFlag=input_args.substring(0,1);
                String context=input_args.substring(1);

                if("F".equals(startFlag)){
                    if(context.contains("挂断")) {

                    }else if(context.contains("人工")){

                    }else{
                        //判断电话语音内容，进行回复
                        Map<String,Object>  flowMap=new TreeMap<>();
                        flowMap.put("action","cti_play_and_detect_speech");
                        flowMap.put("argument","'1' '32' '0' '0.3' '127.0.0.1:9988' '120' '800' '5000' '20000' '' '' '"+appid+"' '1' '\\${strftime(%Y-%m-%d)}' 'wav'");
                        flowMap.put("privatedata","complete");
                        List<String>  playbacksList=new ArrayList<>();
                        playbacksList.add("回复内容"+context);
                        flowMap.put("playbacks",playbacksList);
                        return JSONObject.toJSONString(flowMap);
                    }

                }else{
                    //
                }

            }else if("complete".equals(input_type)){//动作完成

                if("start".equals(flowVo.getPrivatedata())){
                    Map<String,Object>  flowMap=new TreeMap<>();
                    flowMap.put("action","cti_play_and_detect_speech");
                    flowMap.put("argument","'1' '32' '0' '0.3' '127.0.0.1:9988' '120' '800' '5000' '20000' '' '' '"+appid+"' '1' '\\${strftime(%Y-%m-%d)}' 'wav'");
                    flowMap.put("privatedata","complete");
                    List<String>  playbacksList=new ArrayList<>();
                    playbacksList.add("动作完成，请说话");
                    flowMap.put("playbacks",playbacksList);
                    return JSONObject.toJSONString(flowMap);
                }

            }else if("dtmf".equals(input_type)) {//按键完成

            }
        }
        return null;
    }



    private void process(List<TaskRecord> taskRecords) {
        //本周开始时间
        String thisWeekStartTime= DateUtil2.getStartOrEndDayOfWeek(null,true    );
        String thisWeekEndTime= DateUtil2.getStartOrEndDayOfWeek(null,false    );

        //上周开始时间和结束时间
        String lastWeekStartTime=DateUtil2.getLastWeekStartOrEndDayOfWeek().get("beginTime");
        String lastWeekEndTime=DateUtil2.getLastWeekStartOrEndDayOfWeek().get("endTime");

        //昨天时间
        String beforeOneDay = DateUtil.getBeforeOneDay(new Date());

        //本月开始时间
        String thisMonthStartTime = DateUtil2.getStartOrEndDayOfMonth(null, true);
        String thisMonthEndTime = DateUtil2.getStartOrEndDayOfMonth(null, false);
        //上月开始时间
        String lastMonthStartTime = DateUtil2.getLastStartOrEndDayOfMonth().get("beginTime");
        String lastMonthEndTime = DateUtil2.getLastStartOrEndDayOfMonth().get("endTime");


        for (TaskRecord recordVo : taskRecords) {
            Integer id = recordVo.getId();//

            //查询上个月的数据
            Wrapper<TaskRecord> wrm=new EntityWrapper<>();
            wrm.eq("task_id",recordVo.getTaskId());
            List<TaskRecord> recordListVo = this.selectList(wrm);
            if(!CollectionUtils.isEmpty(recordListVo)){

                Integer thisWeekTotal=0;
                Integer lastWeekTotal=0;
                Integer yesterdayNum=0;

                Integer thisMonthTotal=0;
                Integer lastMonthTotal=0;

                for (TaskRecord record : recordListVo) {
                    String addTime = record.getAddTime();
                    //本周数据
                    if(DateUtil.compareDate(addTime,thisWeekEndTime) &&DateUtil.compareDate(thisWeekStartTime,addTime)){
                        Integer once = record.getOnce();
                        thisWeekTotal+=once;
                    }
                    //上周数据
                    if(DateUtil.compareDate(addTime,lastWeekEndTime) &&DateUtil.compareDate(lastWeekStartTime,addTime)){
                        Integer once = record.getOnce();
                        lastWeekTotal+=once;
                    }
                    //昨天数据
                    if(addTime.equals(beforeOneDay)){
                        yesterdayNum=record.getOnce();
                    }

                    //本月数据
                    if(DateUtil.compareDate(addTime,thisMonthEndTime) &&DateUtil.compareDate(thisMonthStartTime,addTime)){
                        Integer once = record.getOnce();
                        thisMonthTotal+=once;
                    }

                    //上月数据
                    if(DateUtil.compareDate(addTime,lastMonthEndTime) &&DateUtil.compareDate(lastMonthStartTime,addTime)){
                        Integer once = record.getOnce();
                        lastMonthTotal+=once;
                    }

                }
                recordVo.setThisMonth(thisMonthTotal+"");
                recordVo.setLastMonth(lastMonthTotal+"");
                recordVo.setYesterday(yesterdayNum+"");
                recordVo.setThisWeek(thisWeekTotal+"");
                recordVo.setLastWeek(lastWeekTotal+"");
            }
        }
    }

    /**
     * 完成，添加属性自定义，
     * 可以添加完成。、
     * 等同于规格
     * json存储
     *
     * 查询全部?
     * sku
     * 标志位，是否完成
     * 类型
     * once time 频率
     * 完成条件
     * 记录次数
     * 记录时间
     * 如果又要记录次数，又要记录时间呢？
     * 按钮，时间
     * 按钮，次数
     * 按钮，。。。
     * 番茄钟
     * 完成条件套娃？
     *
     * 完成条件json拼接
     *  1 2 3
     *  11 12 13
     *
     *  11完成
     *  12完成
     *  13完成
     *
     *  完成的时候同步数据
     *  //计算套娃更新
     *
     */
}
